<template>
  <div class="app-container">

    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="searchForm" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" placeholder="输入博客" v-model="searchForm.condition"></el-input>
        <el-radio-group v-model="searchForm.method">
          <el-radio label="title"></el-radio>
          <el-radio label="content"></el-radio>
          <el-radio label="intro"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>

      <el-table-column prop="blogId" label="博客id" >
      </el-table-column>

      <el-table-column prop="blogTitle" label="博客标题" >
      </el-table-column>

      <el-table-column prop="blogIntro" label="博客简介">
      </el-table-column>

      <el-table-column prop="blogCreateUser" label="博客创建者">
      </el-table-column>

      <el-table-column sortable label="创建时间">
        <template slot-scope="scope">
          {{scope.row.blogCreateTime| dateFormat }}
        </template>
      </el-table-column>

      <el-table-column sortable prop="blogViews" label="博客浏览量" >
      </el-table-column>


      <el-table-column sortable prop="blogLastChangeTime" label="博客上次修改时间">
        <template slot-scope="scope">
          {{scope.row.blogLastChangeTime| dateFormat }}
        </template>
      </el-table-column>

      <el-table-column prop="blogTag" label="标签">
      </el-table-column>


      <el-table-column sortable prop="blogLike" label="like数量">
      </el-table-column>
      <el-table-column label="封面">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.blogCover"
            :preview-src-list="[scope.row.blogCover]"
          >
          </el-image>
        </template>
      </el-table-column>

      <el-table-column prop="blogDelete" label="逻辑删除">
        <template slot-scope="scope">
          <span v-if="scope.row.blogDelete == 1" style="color:red">
            <i class="el-icon-delete">已被逻辑删除</i>
          </span>
          <span v-else style="color: #36a3f7">
             未删除
          </span>
        </template>
      </el-table-column>

      <el-table-column width="300" align="center" label="操作" >
        <template slot-scope="scope">
          <el-button size="mini" icon="el-icon-edit" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <span v-if="scope.row.blogDelete == 1">
            <el-button size="mini" icon="el-icon-delete" type="warning" @click="deleteUser(scope.$index, scope.row)">撤销删除</el-button>
          </span>
          <span v-else style="color: #36a3f7">
            <el-button size="mini" icon="el-icon-delete" type="danger" @click="deleteUser(scope.$index, scope.row)">逻辑删除</el-button>
          </span>

          <blog-comment :blog-id="scope.row.blogId"></blog-comment>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        layout="prev, pager, next"
        :page-size="8"
        :current-page="pageParam.current"
        :total="pageParam.total"
        @next-click="nextPage"
        @prev-click="prevPage"
        @current-change="currentChange"
      >
      </el-pagination>
    </div>
    <!-- 编辑界面 -->
    <el-dialog :visible="editFormVisible" width="90%" @click="closeDialog">
      <!-- 可以修改标题和简介-->
      <el-form label-width="120px" :model="editForm" >

          <el-form-item label="博客标题" prop="blogTitle">
            <el-input size="small" v-model="editForm.blogTitle" placeholder="请输入博客标题"></el-input>
          </el-form-item>
          <el-form-item label="博客简介" prop="blogIntro">
            <el-input size="small" v-model="editForm.blogIntro" placeholder="请输入博客内容简介"></el-input>
          </el-form-item>
          <el-form-item label="博客标签" >
            <el-select v-model="tagNameNow" placeholder="请选择标签">
              <el-option
                v-for="item in tagOptions"
                :key="item.tagId"
                :label="item.tagName"
                :value="item.tagName">
                <!--           label为显示的name   -->
                <!--            v-model的值为当前被选中的el-option的 value 属性值  -->
              </el-option>
            </el-select>
          </el-form-item>


          <el-form-item label="博客封面" >
            <uploadCover @submit-url="updateCoverUrl" :blogImgUrl="editForm.blogCover"></uploadCover>
          </el-form-item>

        <el-form-item  prop="blogContent">
          <mavon-editor
            style="width:100%;height: 100%"
            :html="true"
            v-model="editForm.blogContent"
            :xssOptions="{
                whiteList: {
                    iframe: ['src', 'height', 'width', 'scrolling','allowfullscreen','frameborder'],
                    div: ['style', 'height', 'width', 'align'],
                    img: ['src', 'height', 'width','style', 'align']
                  }
              }"
          ></mavon-editor>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {
  blogDelete,
  blogDeleteCancel,
  blogSave,
  blogsGet,
  blogsGetWithDelete,
  blogsSearch,
  commentsGet
} from "@/api/blog";
import BlogComment from "@/views/blog/blogComment";
import {tagsGet} from "@/api/tag";
import uploadCover from "@/views/blog/uploadCover";

export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',
      editForm: {
        blogId: '',
        blogIntro: '',
        blogTitle: '',
        blogContent: '',
        blogDelete: '',
        blogTag: '',
        blogCover: ''
      },
      tagNameNow: '',
      tagOptions: [],
      // rules表单验证
      rules: {
        // deptName: [
        //   { required: true, message: '请输入blog名称', trigger: 'blur' }
        // ],
        // deptNo: [{ required: true, message: '请输入blog代码', trigger: 'blur' }]
      },
      searchForm:{
        condition: '',
        method: ''
      },
      listData: [], //用户数据
      commentData: [],
      // 分页参数
      pageParam: {
        total: 0,
        size: 8,
        current: 1,
        pages: 1
      }
    }
  },
  // 注册组件
  components: {
    BlogComment,
    uploadCover
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getBlogList(this.pageParam.current)
    this.getAllTags();
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    nextPage(){
      this.getBlogList(++this.current)
    },
    prevPage(){
      this.getBlogList(--this.current)
    },
    currentChange(val){
      /*修改当前页面为val 来自前端点击数字的值*/
      this.current = val;
      this.getBlogList(this.current);
    },
    getBlogList(page){
      blogsGetWithDelete(page).then(res => {
          this.listData = res.data.records
        }
      ).catch(err => {
          console.error(err);
        }
      )
    }
    ,
    // 搜索事件
    search() {
      blogsSearch(this.searchForm.method,this.searchForm.condition).then(
        res => {
          this.listData = res.data
        }
      )
    },
    getAllTags() {
      /*blogTag为编辑页面现在的id*/
      tagsGet().then(
        res => {
          if (res.code===0){
            this.tagOptions = res.data
          }else {
            /*其他故障*/
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        }
      );
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      //判断是否是编辑，即已经有的数据
      if (row != undefined && row != 'undefined') {

        this.tagNameNow = this.tagOptions.filter(item => item.tagId == row.blogTag)[0].tagName
        const tagUpdateId = this.tagOptions.filter(item => item.tagName == this.tagNameNow)[0].tagId;

        this.title = '修改'
        this.editForm.blogTitle = row.blogTitle
        this.editForm.blogIntro = row.blogIntro
        this.editForm.blogContent = row.blogContent
        this.editForm.blogTag = tagUpdateId
        this.editForm.blogId = row.blogId
        this.editForm.blogCover = row.blogCover

        /*编辑页面让tag替换为现在的那个*/
      } else {
        this.$message({
          type: 'error',
          message: "没有读取到数据"
        })
      }
    },
    // 编辑、增加页面保存方法
    submitForm() {
      /*这里的逻辑：在打开编辑页面的时候，显示的是tagNameNow属性，需要根据blogTag与tagOption进行匹配，把tagName显示出来
      * 在上传的时候，把tagNameNow匹配出他所对应tag表的id，把id导入编辑的表单，即this.editForm.blogTag中进行上传
      * 在上传结束的时候tagNameNow也要更新一下
      * */
      this.editForm.blogTag = this.tagOptions.filter(item => item.tagName == this.tagNameNow)[0].tagId

      blogSave(this.editForm)
        .then(res => {
          this.editFormVisible = false
          this.loading = false
          if (res.code===0) {
            this.$message({
              type: 'success',
              message: res.msg
            })

          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
          this.getBlogList(this.pageParam.current)  /*刷新一下*/
          //此时tagNameNow也要更新
          this.tagNameNow = this.tagOptions.filter(item => item.tagId == this.editForm.blogTag)[0].tagName
        })
        .catch(err => {
          this.editFormVisible = false
          this.loading = false
          this.$message.error('blog保存失败，请稍后再试！'+err)
        })
    },
    // 删除blog
    deleteUser(index, row) {

      if (row.blogDelete===0){
        /*还没逻辑删除*/
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            blogDelete(row.blogId)
              .then(res => {
                if (res.code===0) {
                  this.$message({
                    type: 'success',
                    message: 'blog已删除!'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
                this.getBlogList(this.pageParam.current)
              })
              .catch(err => {
                this.loading = false
                this.$message.error('blog删除失败，请稍后再试！err:'+err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      }else {

        this.$confirm('确定要撤销删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            blogDeleteCancel(row.blogId)
              .then(res => {
                if (res.code===0) {
                  this.$message({
                    type: 'success',
                    message: 'blog已撤销删除!'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
                this.getBlogList(this.pageParam.current)
              })
              .catch(err => {
                this.loading = false
                this.$message.error('blog删除失败，请稍后再试！err:'+err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })

      }


    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },
    /*上传图片的地址进行更新*/
    updateCoverUrl(para){
      this.editForm.blogCover = para;
    }
  }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>


